<template>
  <el-dialog
    :title="id?'修改':'添加'"
    :visible.sync="dialogVisible"
    width="800px"
    :show="show"
    :before-close="handleClose"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    @open='open'>
    <el-form ref="form" :model="info" label-width="90px" :rules="rules"
             v-loading="infoLoading">
      <div class="el-dialog-div form-scrollbar">
      <el-row>
        <el-col :span="12">
          <el-form-item label="客户名称" prop="name">
            <el-input type="text" v-model="info.name"
                      placeholder="请填写客户名称" maxlength="255"/>
          </el-form-item>
          <el-form-item label="电话" >
            <el-input type="text" v-model="info.mobile"
                      placeholder="请填写客户电话" maxlength="255"/>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input type="text" v-model="info.email"
                      placeholder="请填写客户邮箱" maxlength="255"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="职称">
            <el-input type="text" v-model="info.jobTitle"
                      placeholder="请填写客户职称" maxlength="255"/>
          </el-form-item>
          <el-form-item label="公司电话">
            <el-input type="text" v-model="info.companyTel"
                      placeholder="请填写客户公司电话" maxlength="255"/>
          </el-form-item>
          <el-form-item label="领英网址">
            <el-input type="text" v-model="info.linkedinUrl"
                      placeholder="请填写客户领英网址" maxlength="255"/>
          </el-form-item>
        </el-col>
      </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="类型" prop="type">
              <el-select
                :disabled="Boolean(this.id)"
                v-model="info.type"
                class="filter-left"
                placeholder="请选择类型"
                clearable
                filterable
                size="small"
              >
                <el-option v-for="item in typeOptions" :label="item.label" :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="来源">
              <el-select
                v-model="info.sourceId"
                class="filter-left"
                placeholder="请选择来源"
                clearable
                filterable
                size="small"
              >
                <el-option v-for="item in sourceOptions" :label="item.name" :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="分组">
              <el-select
                v-model="info.groupId"
                class="filter-left"
                placeholder="请选择分组"
                clearable
                filterable
                size="small"
              >
                <el-option v-for="item in groupOptions" :label="item.name" :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注">
          <el-input type="textarea" v-model="info.remarks" :rows="6"></el-input>
        </el-form-item>
        <el-form-item label="关注度">
          <el-rate
            style="line-height: 2.4"
            v-model="info.attention"
            :colors="colors">
          </el-rate>
        </el-form-item>
      </div>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-row>
        <el-col :span="12" class="btnEdit">
          <el-button :disabled="infoLoading" type="primary" @click="subInfo()">保存</el-button>
        </el-col>
        <el-col :span="12" class="btnEdit">
          <el-button @click="handleClose">取消</el-button>
        </el-col>
      </el-row>
    </div>
  </el-dialog>
</template>

<script>
import {createCustomer, getCustomer, updateCustomer} from "@/api/customer";
import {getSourceCollect} from "@/api/customer/source";
import {getGroupCollect} from "@/api/customer/group";

export default {
  name: "edit",
  props: {
    show: {
      type: Boolean,
      default: false
    },
    id: '',
    blockId: '',
    closeAction: '',
    origin: {
      type: Number,
      default: 1
    },
  },
  data() {
    let checkPhone = (rule, value, callback) => {
      const phoneReg = /^1[3|4|5|7|8][0-9]{9}$/
      if (!value) {
        return callback(new Error('电话号码不能为空'))
      }
      setTimeout(() => {
        if (!Number.isInteger(+value)) {
          callback(new Error('请输入数字值'))
        } else {
          if (phoneReg.test(value)) {
            callback()
          } else {
            callback(new Error('电话号码格式不正确'))
          }
        }
      }, 100)
    }
    let checkEmail = (rule, value, callback) => {
      const mailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
      if (!value) {
        return callback(new Error('邮箱不能为空'))
      }
      setTimeout(() => {
        if (mailReg.test(value)) {
          callback()
        } else {
          callback(new Error('请输入正确的邮箱格式'))
        }
      }, 100)
    }
    return {
      colors: ['#99A9BF', '#F7BA2A', '#FF9900'],
      info: {},
      tempData: {
        name: '',
        mobile: '',
        email: '',
        linkedinUrl: '',
        sourceId: '',
        groupId: '',
        type: '',
        jobTitle: '',
        companyTel:'',
        attention: 0,
        remarks: '',
        isIntention: 0
      },
      typeOptions: [
        {label: '全球搜索', value: 1},
        {label: '数据营销', value: 2},
        {label: '外部导入', value: 3},
      ],
      sourceOptions: [],
      groupOptions: [],
      dialogVisible: this.show,
      infoLoading: false,
      isChange: false,
      initForm: false,
      rules: {
        name: [{required: true, message: '请填写客户名称', trigger: 'blur'}],
        mobile: [{required: true, validator: checkPhone, trigger: 'blur'}],
        email: [{required: true, validator: checkEmail, trigger: 'blur'}],
        type: [{required: true, message: '请选择类型', trigger: 'blur'}],
      },
    }
  },
  methods: {
    async open() {
      this.$nextTick(() => {
        this.$refs['form'].clearValidate()
      })
      this.infoLoading = true
      if (this.id != '') {
        const {data} = await getCustomer(this.id)
        if (data.groupId == 0) {
          data.groupId = ''
        }
        if (data.sourceId == 0) {
          data.sourceId = ''
        }
        this.info = data
      } else {
        this.resetTempData()
        this.info = this.tempData
      }
      this.initForm = true
      //获取来源
      await getSourceCollect().then((res) => {
        this.sourceOptions = res.data
      })
      //获取分组
      await getGroupCollect().then((res) => {
        this.groupOptions = res.data
      })
      setTimeout(() => {
        this.infoLoading = false
      }, 0.5 * 1000)
    },
    handleClose(done) {
      if (this.isChange) {
        this.$confirm('您有未保存的修改，确定关闭此页吗？', '提示', {
          type: 'warning'
        })
          .then(_ => {
            this.$emit('update:show', false)
          })
          .catch(_ => {
          })
      } else {
        this.$emit('update:show', false)
      }
    },
    resetTempData() {
      this.tempData = {
        name: '',
        mobile: '',
        email: '',
        linkedinUrl: '',
        sourceId: '',
        groupId: '',
        type: '',
        company: '',
        jobTitle: '',
        companyTel:'',
        attention: 0,
        remarks: '',
        isIntention: 0,
      }
    },
    subInfo() {
      this.$refs['form'].validate(async (valid) => {
        if (valid) {
          this.infoLoading = true
          let data = this.info
          if (data.groupId == '') {
            data.groupId = 0
          }
          if (data.sourceId == '') {
            data.sourceId = 0
          }
          data.origin = this.origin;
          data.blockId = this.blockId;
          if (this.id != '') {
            await updateCustomer(this.id, data).then((res) => {
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
              this.$emit('closeAction')
            }).catch(() => {
              setTimeout(() => {
                this.infoLoading = false
              }, 0.5 * 1000)
            })
          } else {
            await createCustomer(data).then((res) => {
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 2000
              })
              this.$emit('closeAction')
            }).catch(() => {
              setTimeout(() => {
                this.infoLoading = false
              }, 0.5 * 1000)
            })
          }
        }
      })
    }
  },
  watch: {
    show() {
      this.dialogVisible = this.show
    },
    tempData: {
      handler: function () {
        if (this.initForm) {
          this.isChange = false
          this.initForm = false
        } else {
          this.isChange = true
        }
      },
      deep: true
    }
  }
}
</script>

<style scoped>
.form-scrollbar {
  height: 450px !important;
}

/deep/ textarea {
  resize: none;
}
</style>
